package com.kaifamiao.wendao.service;

import com.kaifamiao.wendao.dao.CommentDao;
import com.kaifamiao.wendao.dao.CustomerDao;
import com.kaifamiao.wendao.dao.TopicDao;
import com.kaifamiao.wendao.entity.Comment;
import com.kaifamiao.wendao.entity.Customer;
import com.kaifamiao.wendao.entity.Topic;

import java.time.LocalDateTime;
import java.util.List;

public class TopicService {

    private TopicDao topicDao = new TopicDao();
    private CustomerDao customerDao = new CustomerDao();
    private CommentDao commentDao = new CommentDao();

    public boolean save( Topic t ) {
        t.setId( topicDao.nextId() );
        t.setPublishTime( LocalDateTime.now() );
        return topicDao.save( t );
    }

    /**
     * 统计总页数
     * @param pageSize 每页显示的行数
     * @return 返回总页数
     */
    public Integer countPages( int pageSize ) {
        int count = topicDao.count();
        return count / pageSize + ( count % pageSize == 0 ? 0 : 1 ) ;
    }

    /**
     * 分页查询
     * @param current 查询第几页
     * @param pageSize 每页显示的行数
     * @return
     */
    public List<Topic> paging( int current , int pageSize ) {
        int start = ( current - 1 ) * pageSize ;
        return topicDao.paging( start , pageSize );
    }

    public Integer countMinePages( int customerId , int pageSize){
        int count = topicDao.countMine( customerId );
        return count / pageSize + ( count % pageSize == 0 ? 0 : 1 ) ;
    }

    public List<Topic> loadAll(){
        List<Topic> list = topicDao.findAll() ;
        for( Topic t : list ){
            Customer p = t.getPublisher() ;
            System.out.println( p );
            // 使用已经再 Topic 中存在的 Customer 对象的 id 来查询
            Customer c = customerDao.find( p.getId() );
            System.out.println( p );
            t.setPublisher( c );
        }
        return list ;
    }

    public Topic load( Integer id ) {
        Topic t = topicDao.find( id );

        Customer p = t.getPublisher();
        Customer c = customerDao.find( p.getId() );
        t.setPublisher( c );

        List<Comment> comments = commentDao.findByTopicId( id );
        for( Comment comment : comments ){
            Customer publisher = comment.getPublisher() ;
            // 使用已经在 Comment 中存在的 Customer 对象的 id 来查询
            publisher = customerDao.find( publisher.getId() );
            comment.setPublisher( publisher );
        }
        t.setComments( comments );
        return t ;
    }

    public List<Topic> loadMine( int customerId , int current , int pageSize ){
        int start = ( current - 1 ) * pageSize ;
        List<Topic> list = topicDao.findMine( customerId , start , pageSize ) ;
        return list ;
    }

    public boolean remove( Integer id ) {
        return topicDao.remove( id );
    }
}
